// 加载购物车数据
async function loadCartItems() {
    try {
        const response = await fetch('/cart');
        const cartItems = await response.json();
        const tbody = document.querySelector('tbody');

        // 清空现有内容
        tbody.innerHTML = '';

        if (cartItems.length === 0) {
            // 显示购物车为空的信息
            showEmptyCart();
            return;
        }

        // 为每个商品创建表格行
        cartItems.forEach(item => {
            const subtotal = item.price * item.quantity;
            const row = document.createElement('tr');
            row.innerHTML = `
                <td><input type="checkbox" class="form-check-input item-checkbox" checked></td>
                <td>
                    <img src="${item.image}" alt="${item.name}" class="img-thumbnail" style="max-width: 80px;">
                </td>
                <td>${item.name}</td>
                <td>¥${item.price.toFixed(1)}</td>
                <td>
                    <div class="input-group quantity-selector">
                        <button class="btn btn-outline-secondary minus">-</button>
                        <input type="number" class="form-control text-center" value="${item.quantity}" min="1">
                        <button class="btn btn-outline-secondary plus">+</button>
                    </div>
                </td>
                <td>¥${subtotal.toFixed(1)}</td>
                <td>
                    <button class="btn btn-sm btn-outline-danger" data-id="${item.id}"><i class="bi bi-trash"></i> 删除</button>
                </td>
            `;
            tbody.appendChild(row);
        });

        // 重新绑定事件
        initQuantityControls();
        initSelectAll();
        initDeleteButtons();

        // 更新总金额
        updateTotal();
    } catch (error) {
        console.error('加载购物车数据失败:', error);
    }
}

// 显示空购物车提示
function showEmptyCart() {
    const tbody = document.querySelector('tbody');
    tbody.innerHTML = `
        <tr>
            <td colspan="7" class="text-center py-5">
                <div class="empty-cart-message">
                    <i class="bi bi-cart-x" style="font-size: 3rem;"></i>
                    <h4 class="mt-3">您的购物车是空的</h4>
                    <p class="text-muted">快去挑选心仪的商品吧</p>
                    <a href="文创商城.html" class="btn btn-primary mt-3">去逛逛</a>
                </div>
            </td>
        </tr>
    `;

    // 禁用全选和提交按钮
    document.getElementById('selectAll').disabled = true;
    document.querySelector('.cart-actions .btn-primary').disabled = true;
}

// 删除单个商品
async function initDeleteButtons() {
    document.querySelectorAll('.btn-outline-danger').forEach(btn => {
        btn.addEventListener('click', async function() {
            const productId = this.dataset.id;
            if (confirm('确定要删除这个商品吗？')) {
                try {
                    const response = await fetch(`/cart/${productId}`, {
                        method: 'DELETE'
                    });
                    const data = await response.json();
                    if (response.ok) {
                        // 重新加载购物车
                        loadCartItems();
                    } else {
                        console.error('删除商品失败:', data.message);
                    }
                } catch (error) {
                    console.error('删除商品时发生错误:', error);
                }
            }
        });
    });
}

// 清空购物车
async function initClearCart() {
    const clearCartBtn = document.querySelector('.cart-actions .btn-outline-secondary');
    if (clearCartBtn) {
        clearCartBtn.addEventListener('click', async function() {
            if (confirm('确定要清空购物车吗？')) {
                try {
                    const response = await fetch('/cart', {
                        method: 'DELETE'
                    });
                    const data = await response.json();
                    if (response.ok) {
                        // 重新加载购物车
                        loadCartItems();
                    } else {
                        console.error('清空购物车失败:', data.message);
                    }
                } catch (error) {
                    console.error('清空购物车时发生错误:', error);
                }
            }
        });
    }
}

// 更新小计
async function updateSubtotal(row) {
    const price = parseFloat(row.querySelector('td:nth-child(4)').textContent.replace('¥', ''));
    const quantity = parseInt(row.querySelector('.quantity-selector input').value);
    const subtotal = price * quantity;
    row.querySelector('td:nth-child(6)').textContent = '¥' + subtotal.toFixed(1);

    // 更新后端的数量
    const productId = row.querySelector('.btn-outline-danger').dataset.id;
    try {
        const response = await fetch(`/cart/${productId}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ quantity: quantity })
        });
        const data = await response.json();
        if (!response.ok) {
            console.error('更新商品数量失败:', data.message);
        }
    } catch (error) {
        console.error('更新商品数量时发生错误:', error);
    }
}

// 在DOM加载完成后调用
document.addEventListener('DOMContentLoaded', async function() {
    await loadCartItems();
    // 其他初始化代码...
});

// 购物车功能实现
document.addEventListener('DOMContentLoaded', function() {
    // 初始化数量增减功能
    initQuantityControls();

    // 初始化全选功能
    initSelectAll();

    // 初始化删除按钮
    initDeleteButtons();

    // 初始化清空购物车按钮
    initClearCart();

    // 初始化提交订单按钮
    initSubmitOrder();

    // 初始化支付方式切换
    initPaymentMethods();

    // 初始化复制订单号功能
    initCopyOrderNum();

    // 初始计算总金额
    updateTotal();
});

// 数量增减功能
function initQuantityControls() {
    document.querySelectorAll('.minus').forEach(btn => {
        btn.addEventListener('click', async function() {
            const input = this.nextElementSibling;
            if (parseInt(input.value) > 1) {
                input.value = parseInt(input.value) - 1;
                await updateSubtotal(this.closest('tr'));
                updateTotal();
            }
        });
    });

    document.querySelectorAll('.plus').forEach(btn => {
        btn.addEventListener('click', async function() {
            const input = this.previousElementSibling;
            input.value = parseInt(input.value) + 1;
            await updateSubtotal(this.closest('tr'));
            updateTotal();
        });
    });

    // 手动输入数量变化事件
    document.querySelectorAll('.quantity-selector input').forEach(input => {
        input.addEventListener('change', async function() {
            if (parseInt(this.value) < 1) this.value = 1;
            await updateSubtotal(this.closest('tr'));
            updateTotal();
        });
    });
}

// 全选功能
function initSelectAll() {
    const selectAllCheckbox = document.getElementById('selectAll');
    if (selectAllCheckbox) {
        selectAllCheckbox.addEventListener('change', function() {
            document.querySelectorAll('.item-checkbox').forEach(checkbox => {
                checkbox.checked = this.checked;
            });
            updateTotal();
        });

        // 单个商品选择变化时检查全选状态
        document.querySelectorAll('.item-checkbox').forEach(checkbox => {
            checkbox.addEventListener('change', function() {
                const allChecked = document.querySelectorAll('.item-checkbox:not(:checked)').length === 0;
                selectAllCheckbox.checked = allChecked;
                updateTotal();
            });
        });
    }
}

// 更新总金额
function updateTotal() {
    let total = 0;
    let points = 0;
    let selectedCount = 0;

    document.querySelectorAll('tbody tr').forEach(row => {
        const checkbox = row.querySelector('.item-checkbox');
        if (!checkbox || checkbox.checked) {
            const price = parseFloat(row.querySelector('td:nth-child(4)').textContent.replace('¥', ''));
            const quantity = parseInt(row.querySelector('.quantity-selector input').value);
            total += price * quantity;
            points += price * quantity * 2; // 假设积分是金额的2倍
            selectedCount++;
        }
    });

    // 更新总金额和积分
    document.querySelector('.payment-amount span').textContent = '¥' + total.toFixed(1);
    document.querySelector('.discount-info .text-primary').textContent = points.toFixed(1);

    // 更新商品金额
    document.querySelector('.discount-info .fw-bold').textContent = '¥' + total.toFixed(1) + '元';

    // 更新提交订单按钮状态
    const submitBtn = document.querySelector('.cart-actions .btn-primary');
    if (submitBtn) {
        submitBtn.disabled = selectedCount === 0;
    }
}

// 提交订单功能
function initSubmitOrder() {
    const submitOrderBtn = document.querySelector('.cart-actions .btn-primary');
    if (submitOrderBtn) {
        submitOrderBtn.addEventListener('click', function() {
            // 检查是否有选中的商品
            const selectedItems = document.querySelectorAll('.item-checkbox:checked');
            if (selectedItems.length === 0) {
                alert('请至少选择一件商品');
                return;
            }

            // 计算总金额
            let total = 0;
            selectedItems.forEach(item => {
                const row = item.closest('tr');
                const subtotal = parseFloat(row.querySelector('td:nth-child(6)').textContent.replace('¥', ''));
                total += subtotal;
            });

            // 生成随机订单号
            const orderNum = 'WC' + new Date().getTime().toString().slice(-6);

            // 更新支付信息
            updatePaymentInfo(total, orderNum, 'alipay');

            // 显示支付模态框
            const paymentModal = new bootstrap.Modal(document.getElementById('paymentModal'));
            paymentModal.show();

            // 模拟支付状态检查
            simulatePaymentCheck();
        });
    }
}

// 支付方式切换
function initPaymentMethods() {
    document.querySelectorAll('.list-group-item').forEach(item => {
        item.addEventListener('click', function(e) {
            e.preventDefault();

            // 更新活跃状态
            document.querySelector('.list-group-item.active').classList.remove('active');
            this.classList.add('active');

            // 获取支付方式
            const method = this.dataset.method;
            const amount = parseFloat(document.querySelector('.payment-amount span').textContent.replace('¥', ''));
            const orderNum = document.querySelector('.payment-instructions input').value;

            // 更新支付信息
            updatePaymentInfo(amount, orderNum, method);
        });
    });
}

// 更新支付信息
function updatePaymentInfo(amount, orderNum, method) {
    // 更新金额
    document.querySelector('.payment-amount span').textContent = '¥' + amount.toFixed(1);

    // 更新订单号
    document.querySelector('.payment-instructions input').value = orderNum;

    // 更新支付方式和二维码
    let methodName = '';
    let qrData = '';
    let instructions = '';

    switch (method) {
        case 'alipay':
            methodName = '支付宝';
            qrData = `https://alipay.com/pay?amount=${amount}&orderNum=${orderNum}`;
            instructions = '请使用支付宝扫描二维码完成支付';
            break;
        case 'wechatpay':
            methodName = '微信支付';
            qrData = `weixin://wxpay/bizpayurl?amount=${amount}&orderNum=${orderNum}`;
            instructions = '请使用微信扫描二维码完成支付';
            break;
        case 'unionpay':
            methodName = '银联支付';
            qrData = `https://unionpay.com/pay?amount=${amount}&orderNum=${orderNum}`;
            instructions = '请使用云闪付扫描二维码完成支付';
            break;
        case 'bankcard':
            methodName = '银行卡支付';
            qrData = `bank://pay?amount=${amount}&orderNum=${orderNum}`;
            instructions = '请输入您的银行卡信息完成支付';
            break;
    }

    // 更新UI
    document.getElementById('currentMethod').textContent = methodName;
    document.getElementById('paymentInstructions').textContent = instructions;
    document.getElementById('qrCodeImage').src = `https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(qrData)}`;

    // 如果是银行卡支付，隐藏二维码区域
    if (method === 'bankcard') {
        document.querySelector('.qr-code-container').classList.add('d-none');
        document.getElementById('paymentInstructions').textContent = '请输入您的银行卡信息完成支付';
    } else {
        document.querySelector('.qr-code-container').classList.remove('d-none');
    }
}

// 复制订单号功能
function initCopyOrderNum() {
    const copyBtn = document.getElementById('copyOrderNum');
    if (copyBtn) {
        copyBtn.addEventListener('click', function() {
            const orderNumInput = document.querySelector('.payment-instructions input');
            orderNumInput.select();
            document.execCommand('copy');

            // 显示复制成功提示
            const originalText = this.innerHTML;
            this.innerHTML = '<i class="bi bi-check"></i> 已复制';
            setTimeout(() => {
                this.innerHTML = originalText;
            }, 2000);
        });
    }
}

// 模拟支付状态检查
function simulatePaymentCheck() {
    // 重置支付状态显示
    document.getElementById('paymentSuccess').classList.add('d-none');
    document.getElementById('paymentFailed').classList.add('d-none');

    setTimeout(() => {
        // 随机模拟支付成功或失败
        const isSuccess = Math.random() > 0.3;

        if (isSuccess) {
            document.getElementById('paymentSuccess').classList.remove('d-none');
            document.getElementById('paymentFailed').classList.add('d-none');

            // 3秒后自动关闭模态框
            setTimeout(() => {
                const paymentModal = bootstrap.Modal.getInstance(document.getElementById('paymentModal'));
                paymentModal.hide();
                alert('支付成功！感谢您的购买！');

                // 清空已购买的商品
                document.querySelectorAll('.item-checkbox:checked').forEach(item => {
                    item.closest('tr').remove();
                });
                updateTotal();
            }, 3000);
        } else {
            document.getElementById('paymentSuccess').classList.add('d-none');
            document.getElementById('paymentFailed').classList.remove('d-none');
        }
    }, 3000);
}
